package com.zzyl.nursing.service.impl;

import java.util.HashMap;
import java.util.List;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.dto.UserLoginRequestDto;
import com.zzyl.nursing.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.domain.FamilyMember;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.Arrays;
import java.util.Map;

/**
 * 老人家属Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-12-12
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService
{
    @Autowired
    private FamilyMemberMapper familyMemberMapper;

    @Autowired
    private TokenService tokenService;


    private static final String WX_OPENID_URL = "https://api.weixin.qq.com/sns/jscode2session";

    private static final String WX_PHONE_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";

    private static final String WX_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";

    private static final String WX_APPID = "wxbac74284423bd4e8";

    private static final String WX_SECRET = "1cf891e6cfdbdace48d2edf363116735";
    static List<String> DEFAULT_NICKNAME_PREFIX = ListUtil.of("生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝"
    );

    /**
     * 查询老人家属
     * 
     * @param id 老人家属主键
     * @return 老人家属
     */
    @Override
    public FamilyMember selectFamilyMemberById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询老人家属列表
     * 
     * @param familyMember 老人家属
     * @return 老人家属
     */
    @Override
    public List<FamilyMember> selectFamilyMemberList(FamilyMember familyMember)
    {
        return familyMemberMapper.selectFamilyMemberList(familyMember);
    }

    /**
     * 新增老人家属
     * 
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int insertFamilyMember(FamilyMember familyMember)
    {
        return save(familyMember) ? 1 : 0;
    }

    /**
     * 修改老人家属
     * 
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int updateFamilyMember(FamilyMember familyMember)
    {
        return updateById(familyMember) ? 1 : 0;
    }

    /**
     * 批量删除老人家属
     * 
     * @param ids 需要删除的老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除老人家属信息
     * 
     * @param id 老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    /**
     *  小程序登录
     * @param dto
     * @return
     */
    @Override
    public LoginVo login(UserLoginRequestDto dto) {
        //1.获取openId
        String openId = getOpenId(dto);
        //2.判断数据库中有没有openid
        FamilyMember familyMember = familyMemberMapper.selectOne(Wrappers.<FamilyMember>lambdaQuery().eq(FamilyMember::getOpenId, openId));
        //2.1.如果为空封装到对象中
        if (ObjectUtils.isEmpty(familyMember)) {
            familyMember = new FamilyMember();
            familyMember.setOpenId(openId);
        }
        //2.2.如果不为空执行修改操作
        //3.根据phonecode获取手机号
        String phone = getphone(dto);
        //4. 新增或者修改
        insertOrUpdate(familyMember,phone);
        //5.返回token
        // 6.将用户id存入token,返回
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", familyMember.getId());
        claims.put("nickName", familyMember.getName());

        String token = tokenService.createToken(claims);
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        loginVo.setNickName(familyMember.getName());
        return loginVo;
    }

    private void insertOrUpdate(FamilyMember familyMember, String phone) {
        if (familyMember.getId() == null) {
            //执行新增操作
            familyMember.setPhone(phone);
            familyMember.setName(DEFAULT_NICKNAME_PREFIX.get((int) (Math.random() * DEFAULT_NICKNAME_PREFIX.size()))
                    + StringUtils.substring(phone, 7));
            save(familyMember);
        }else {
            //执行修改操作
            if (!StringUtils.equals(familyMember.getPhone(), phone)){
                familyMember.setPhone(phone);
            }
             updateById(familyMember);
        }
    }

    public String getToken() {
        HashMap map = new HashMap();
        map.put("grant_type", "client_credential");
        map.put("appid", WX_APPID);
        map.put("secret", WX_SECRET);
        String result = HttpUtil.get(WX_TOKEN_URL, map);
        JSONObject entries = JSONUtil.parseObj(result);
        return (String) entries.get("access_token");
    }



    public String getphone(UserLoginRequestDto dto) {
        String access_token = getToken();
        HashMap map = new HashMap();
        map.put("code", dto.getPhoneCode());
        String result = HttpUtil.post(WX_PHONE_URL+access_token, JSONUtil.toJsonStr(map));

        JSONObject entries = JSONUtil.parseObj(result);

        String phoneInfo = entries.getStr("phone_info");
        JSONObject phoneInfoJson = JSONUtil.parseObj(phoneInfo);
        return phoneInfoJson.getStr("phoneNumber");
    }


    public String getOpenId(UserLoginRequestDto dto) {
        HashMap map = new HashMap();
        map.put("appid", WX_APPID);
        map.put("secret", WX_SECRET);
        map.put("js_code", dto.getCode());
        map.put("grant_type", "authorization_code");
        String result = HttpUtil.get(WX_OPENID_URL, map);
        JSONObject entries = JSONUtil.parseObj(result);
        return entries.getStr("openid");
    }

    //    public String getphone(UserLoginRequestDto dto) {
//        HashMap map = new HashMap();
//        map.put("code", dto.getPhoneCode());
//        HttpResponse response = HttpUtil.createPost(WX_PHONE_URL + getToken())
//                .body(JSONUtil.toJsonStr(map))
//                .execute();
//        String body = response.body();
//        JSONObject entries = JSONUtil.parseObj(body);
//        String phoneInfo = entries.getStr("phone_info");
//        JSONObject phoneInfoJson = JSONUtil.parseObj(phoneInfo);
//        return phoneInfoJson.getStr("phoneNumber");
//    }
}
